#include <head.h>
#include "./wrap.h"
#include "./linkist.h"
void fn(char *p);
void sig_handler(int no)
{
    printf("child sig\n");
    waitpid(-1, NULL, 0);
}
int main(int argc, char **argv)
{
    int maxfd;
    LinkList clientList = LIST_INIT_VALUE;
    int serversocket = Socket(AF_INET, SOCK_STREAM, 0);
    maxfd = serversocket;
    fd_set rset, allset;
    FD_ZERO(&allset);
    FD_SET(serversocket, &allset);
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9000);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    int r;
    // int r=  inet_pton(AF_INET,"127.0.0.1",&(addr.sin_addr.s_addr));
    // if(r ==0){
    //     sys_error("inet_pton");
    // }
    Bind(serversocket, (struct sockaddr *)&addr, sizeof(addr));
    Listen(serversocket, 10);
    struct sockaddr_in client;
    socklen_t l = sizeof(client);
    int fd;
    while (1)
    {
        rset = allset;
        //printf ("before select\n");
        r = select(maxfd + 1, &rset, NULL, NULL, NULL);
        if (r == -1)
        {
            sys_error("select error");
        }
        else if (r > 0)
        {
            if (FD_ISSET(serversocket, &rset))
            {
                memset(&client, 0, sizeof(client));
                fd = Accept(serversocket, (struct sockaddr *)&client, &l);
                char buf[100];
                CLEAR_ARRAY(buf);
                printf("New connection from IP:%s,port:%d\n", inet_ntop(AF_INET, &(client.sin_addr), buf, sizeof(buf)), ntohs(client.sin_port));
                linklistaddNode(&clientList, fd);
                FD_SET(fd, &allset);
                if (maxfd < fd)
                {
                    maxfd = fd;
                }
                --r;
                if (r == 0)
                {
                    continue;
                }
            }
            if (r > 0)
            {
                listnode *p = clientList.node;
                char buf[100];
                for (size_t i = 0; i < clientList.nodenum && r; i++,p = p->next)
                {
                    if (FD_ISSET(p->data, &rset))
                    {
                        r--;
                        CLEAR_ARRAY(buf);
                        int ret = Read(p->data, buf, sizeof(buf));
                        if (ret == 0)
                        {
                            printf("client disconnected\n");
                            Close(p->data);
                            linklistdelnode(&clientList, p->data);
                            FD_CLR(p->data, &allset);
                            continue;
                        }
                        printf("%s\n", buf);
                        fn(buf);
                        Write(p->data, buf, ret);
                    }
                }
            }
        }
    }
    return 0;
}
void fn(char *p)
{
    if (!p)
    {
        return;
    }
    while (*p)
    {
        *p = toupper(*p);
        p++;
    }
}
